<template>
    <h2>watch</h2>
    <div class="person">
       <h2>情况1：监视ref定义的基本类型数据</h2>
      <h2>当前数据{{ sum }}</h2>
      <button @click="changeSum"> 点击+1</button>
      <h2>情况2：监视ref定义的对象类型数据</h2>
      <h2>姓名：{{person.name}},年龄：{{ person.age }}</h2>
      <button @click="changeName">改名字</button>
      <button @click="changeAge">改年龄</button>
      <button @click="changePerson">改人</button>
      <h2>情况3：监视reactive定义的对象类型数据</h2>
      <h2>姓名：{{person2.name}},年龄：{{ person2.age }}</h2>
      <button @click="changeName2">改名字</button>
      <button @click="changeAge2">改年龄</button>
      <button @click="changePerson2">改人</button>
      <h2>情况4：监视对象类型中的某个数据</h2>
      <h2>姓名：{{person2.name}},年龄：{{ person2.age }}</h2>
      <button @click="changeName2">改名字</button>
      <button @click="changeAge2">改年龄</button>
      <button @click="changePerson2">改人</button>
    </div>
</template>

<script lang="ts" setup name="lesson6 vue">
    import {ref,watch,reactive} from 'vue'
    //数据
    let sum = ref(10)
    //方法
    function changeSum(){
        sum.value+=1
    }
    //监视情况1：监视ref定义的基本类型数据 
    //watch(监视对象，回掉函数)
    const stopWatch = watch(sum,(newValue,oldValue)=>{
        console.log("---change---",newValue, oldValue)
        if(newValue>=20){
            stopWatch()
        }
    })

    let person = ref({'name':'zhangsan','age':19})
    function changeName(){
        person.value.name += "~~~";
    }
    function changeAge(){
        person.value.age+=2
    }
    function changePerson(){
        person.value = {'name':'lisi','age':67}
    }
    // 监视2：监视ref定义的对象类型数据，监视的是对象地址，
    watch(person,(newValue,oldValue)=>{
        console.log("---person change---",newValue, oldValue)
    })
    //若想监视对象内部属性变化，则需手动开启深度监视
    // watch(person,(newValue,oldValue)=>{
    //     console.log("---person change---",newValue, oldValue)
    // },{deep:true})

    let person2 = reactive({'name':'zhangsan','age':19})
    function changeName2(){
        person2.name += "~~~";
    }
    function changeAge2(){
        person2.age+=2
    }
    function changePerson2(){
        Object.assign(person2,{'name':'lisi','age':22})
    }
    // 情况3：监视reactive定义的对象类型数据,默认开启深度监视（deep），且无法关闭
    watch(person2,(newValue,oldValue)=>{
        console.log("---person2 change---",newValue, oldValue)
    })

    let person3 = reactive({'name':'zhangsan','age':19,car:{"c1":"大众朗逸","c2":"别克"}})
    function changeName3(){
        person2.name += "~~~";
    }
    function changeAge3(){
        person2.age+=2
    }
    function changePerson3(){
        Object.assign(person3,{'name':'lisi','age':22})
    }
    // 情况4：监视ref或者reactive定义的对象类型数据的某个属性，且该属性是基本类型，需要写成函数   
    watch(()=>{return person3.name},(newValue,oldValue)=>{
        console.log("---person3.name  change---",newValue, oldValue)
    })
</script>
<style scoped>
  .person{
      background-color: skyblue;
      border-radius: 3px;
      padding: 5px;
      margin: 2px 5px 2px 5px;
  }
  li{font-size: 15px;}
</style>